package com.yilin.commons.encrypt;


import com.google.gson.Gson;
import com.itextpdf.text.log.Logger;
import com.itextpdf.text.log.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

/**
 * 服务器加密
 * AES
 **/
public class EncryptUtils {

    private static Logger logger = LoggerFactory.getLogger(EncryptUtils.class);


    /**
     * 生成公钥和私钥
     * */
    public static KeyPairMap genKeyPairMap(){
        return RSAUtil.genKeyPair();
    }

    /**
     * AES加密
     * */
    public static String aesEncrypt(String data,String aesKey){
        return AESUtil.encrypt(data, aesKey);
    }

    /**
     * AES解密
     * */
    public static String aesDecrypt(String data,String aesKey){
        return AESUtil.decrypt(data, aesKey);
    }

    /**
     * 用公钥加密字符串 客户端
     * */
    public static String rsaPublicEncrypt(String data,String publicKey){
        return RSAUtil.encrypt(data, publicKey);
    }

    /**
     * 用私钥解密字符串 服务器
     * */
    public static String rsaPrivateDecrypt(String data,String privateKey){
        return RSAUtil.decrypt(data, privateKey);
    }

    /**
     * 验证一个公钥和一个私钥是否匹配，一般就是加密一个数据，然后解密，看看解密后的结果与原始数据是否一致
     */
    public static boolean validRSAKeyPairMatch(String publicKey, String privateKey) {
        String content = "yl_gg_ff_pt";
        String encryptContent = rsaPublicEncrypt(content, publicKey);
        String decryptContent = rsaPrivateDecrypt(encryptContent, privateKey);
        return content.equals(decryptContent);
    }

    public static String getToken() {
        UUID uuid = UUID.randomUUID();
        long time = System.currentTimeMillis();
        String str = uuid.toString();
        String uuidStr = str.replace("-", "");
        String md5Str = Objects.requireNonNull(Md5Util.md5By16(String.valueOf(time))).toLowerCase();
        return uuidStr + md5Str;
    }

    public static void main(String[] args) {
        Map<String, Object> map = new HashMap<>();
        map.put("name", "John");
        map.put("age", 30);
        map.put("city", "New York");

        // 将 Map 转换为 JSON 字符串
        Gson gson = new Gson();
        String sj = gson.toJson(map);
//        String key = "8fbfcfe862664ead8e0078e88e6db151";
        String ss=aesEncrypt(sj,null);
        System.out.println(ss);
        String sss=aesDecrypt(ss,null);
        System.out.println(sss);
        System.out.println(genKeyPairMap().getPublicKey());
    }
}